const http = require("http");
const express = require("express");
const socketIo = require("socket.io");
const app = express();
const httpServer = http.createServer(app);
const io = socketIo(httpServer);
const userList = {
    // key---->socket.id
    // value---->username
}
app.use(express.json());
app.use(express.static(__dirname));
io.on("connection",function(socket){
    socket.on("alluser",function(content){
        io.emit("say",userList[socket.id]+"说："+content);
    })
    // 进入房间
    socket.on("inRoom",function(username){
        userList[socket.id] = username;
        io.emit("inRoomInfo",Object.keys(userList).length,username)
    })
    // 离开房间
    socket.on("disconnect",function(){
        // 清空当前用户
        const username = userList[socket.id];
        delete userList[socket.id];
        io.emit("outRoomInfo",Object.keys(userList).length,username)
    })

})
app.post("/login",(req,res)=>{
    if(Object.values(userList).includes(req.body.username)){
        res.json({
            ok:-1,
            msg:"您输入的昵称已经存在！"
        });
        return;
    }
    res.json({
        ok:1,
        msg:"成功"
    })
})
httpServer.listen(80,()=>{
    console.log("success");
})
